package com.newsinfo.controller;

import com.newsinfo.pojo.LoginOrRegisterUser;
import com.newsinfo.pojo.Result;
import com.newsinfo.pojo.User;
import com.newsinfo.service.UserService;
import com.newsinfo.utils.JwtUtil;
import com.newsinfo.utils.Md5Util;
import com.newsinfo.utils.ThreadLocalUtil;
import com.newsinfo.validation.OrderedChecks;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     * @return
     */
    @PostMapping("/register")
    public Result register(@Validated(OrderedChecks.class) @RequestBody LoginOrRegisterUser loginOrRegisterUser){
        String username = loginOrRegisterUser.getUsername();
        String password = loginOrRegisterUser.getPassword();
        String rePassword = loginOrRegisterUser.getRePassword();
        //查看用户是否存在
        User user = userService.findByUsername(username);
        if (user == null) {
            //用户不存在
            if (!password.equals(rePassword)) {
                return Result.error("两次密码不一致");
            }
            userService.register(username,password);
            return Result.success();
        } else {
            //用户存在
            return Result.error("用户名已存在");
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("login")
    public Result<String> login(@Validated(OrderedChecks.class) @RequestBody LoginOrRegisterUser loginOrRegisterUser){
        String username = loginOrRegisterUser.getUsername();
        String password = loginOrRegisterUser.getPassword();
        if (username.isEmpty() || password.isEmpty() ) {
            return Result.error("用户名或密码不能为空");
        }
        //查看用户是否存在
        User user = userService.findByUsername(username);
        if (user == null) {
            //用户不存在
            return Result.error("用户名不存在或密码错误");
        }
        //用户存在，判断密码
        if (Md5Util.getMD5String(password).equals(user.getPassword())) {
            //密码正确,生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            String token = JwtUtil.genToken(claims);
            //将token存入redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,12, TimeUnit.HOURS);
            return Result.success(token);

        }
        //密码错误
        return Result.error("用户名不存在或密码错误");
    }

    /**
     * 获取用户详细
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/){
        //先解析token获取用户信息
        /*Map<String, Object> claims = JwtUtil.parseToken(token);
        String username = (String) claims.get("username");*/
        //从ThreadLocal中获取
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        //根据用户名获取用户信息
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    /**
     * 更新用户基本信息
     */
    @PutMapping("/update")
    public Result updateUserInfo(@RequestBody @Validated User user){
        userService.updateUserInfo(user);
        return Result.success();
    }

    /**
     * 更新用户头像
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 更新用户密码
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        stringRedisTemplate.delete(token);
        return userService.updatePwd(params);
    }
}
